package com.itheima.sc.impl.ums;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.sc.api.ums.UmsResourceApi;
import com.itheima.sc.mapper.ums.UmsResourceMapper;
import com.itheima.sc.pojo.ums.UmsResource;
import com.itheima.sc.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

@DubboService
public class UmsResourceServiceImpl implements UmsResourceApi {
    @Autowired
    private UmsResourceMapper umsResourceMapper;

    /**
     * 添加后台资源
     */
    @Override
    public void create(UmsResource umsResource) {
        umsResourceMapper.insert(umsResource);
    }

    /**
     * 根据ID删除后台资源
     */
    @Override
    public void delete(Integer id) {
        umsResourceMapper.deleteById(id);
    }

    /**
     * 分页模糊查询后台资源
     */
    @Override
    public PageResult list(Integer pageNum, Integer pageSize, Integer categoryId, String nameKeyword, String urlKeyword) {
        Page<UmsResource> page = new Page(pageNum, pageSize);

        //构建查询条件
        LambdaQueryWrapper<UmsResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(nameKeyword), UmsResource::getName, nameKeyword);
        wrapper.like(StrUtil.isNotBlank(urlKeyword), UmsResource::getUrl, urlKeyword);
        wrapper.like(categoryId != null, UmsResource::getCategoryId, categoryId);
        wrapper.orderByDesc(UmsResource::getCreateTime);
        umsResourceMapper.selectPage(page, wrapper);

        //封装分页数据
        PageResult pageResult = new PageResult();
        pageResult.setPageSize(pageSize);
        pageResult.setPageNum(pageNum);
        pageResult.setTotal(Convert.toInt(page.getTotal()));
        pageResult.setTotalPage(Convert.toInt(page.getPages()));
        pageResult.setList(page.getRecords());

        //返回结果
        return pageResult;
    }

    /**
     * 查询所有后台资源
     */
    @Override
    public List<UmsResource> listAll() {
        return umsResourceMapper.selectList(null);
    }

    /**
     * 根据ID获取资源详情
     */
    @Override
    public UmsResource getInfoById(Integer id) {
        return umsResourceMapper.selectById(id);
    }

    /**
     * 修改后台资源
     */
    @Override
    public void update(UmsResource umsResource) {
        umsResourceMapper.updateById(umsResource);
    }


}
